package com.fireandsword.system.handle;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fireandsword.system.annotation.NotControllerResponseAdvice;
import com.fireandsword.system.domain.vo.ResultVo;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author Immortal
 * @version 1.0
 * @description TODO
 * @date 2023/12/28 15:14
 */
@RestControllerAdvice(basePackages = {"com.fireandsword.system"})
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //这个是返回值不是ResultVo的情况，或者注释了NotControllerResponseAdvice注解的情况
        return !(returnType.getParameterType().isAssignableFrom(ResultVo.class) ||
                returnType.hasMethodAnnotation(NotControllerResponseAdvice.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //String类型不能直接包装
        if (returnType.getGenericParameterType().equals(String.class)){
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String s = objectMapper.writeValueAsString(new ResultVo(body));
                return s;
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return new ResultVo(body);
    }
}
